﻿#include"SeqList.h"

void ContactLoad(Contact* con) {
	FILE* prb = fopen("contact.txt", "rb");
	if (prb == NULL) {
		perror("fopen rb error!\n");
		return;
	}
	//循环读取⽂件数据
	Info info;
	while (fread(&info, sizeof(Info), 1, prb))
	{
		SLPushBack(con, info);
	}
	printf("历史数据导入通讯录成功！\n");
}

void ContactInit(Contact* pcon){
	SLInit(pcon);
	ContactLoad(pcon);
}

//增加，删除，修改，查找，查看通讯录
void ContactAdd(Contact* pcon){
	//创建联系人结构体变量
	Info info = { 0 };
	printf("请输入联系人姓名\n");
	scanf("%s", info.name);
	printf("请输入联系人年龄\n");
	scanf("%d", &(info.age));
	printf("请输入联系人性别\n");
	scanf("%s", info.gander);
	printf("请输入联系人电话\n");
	scanf("%s", info.tel);
	printf("请输入联系人地址\n");
	scanf("%s", info.addr);

	SLPushBack(pcon, info);
}
int FindByName(Contact* pcon, char name[]) {
	for (int i = 0; i < pcon->size; i++) {
		if (strcmp(pcon->arr[i].name, name) == 0) {
			//找到了
			return i;
		}
	}
	return -1;
}

void ContactDel(Contact* pcon){
	//删除之前先要查找
	//找到了删除 否则不能执行删除
	printf("请输入你要删除的联系人姓名\n");
	char name[NAME_MAX];
	scanf("%s", name);
	int findIndex = FindByName(pcon, name);
	if (findIndex < 0) {
		printf("要删除的联系人不存在！\n");
		return;
	}
	//执行删除操作
	SLErase(pcon, findIndex);
	printf("联系人删除成功！\n");
}

void ContactModify(Contact* pcon) {
	//修改之前先要查找
	//找到了修改 否则不能执行修改
	printf("请输入你要修改的联系人姓名\n");
	char name[NAME_MAX];
	scanf("%s", name);
	int findIndex = FindByName(pcon, name);
	if (findIndex < 0) {
		printf("要修改的联系人不存在！\n");
		return;
	}
	//执行修改操作
	printf("请输入联系人姓名\n");
	scanf("%s", pcon->arr[findIndex].name);
	printf("请输入联系人年龄\n");
	scanf("%d", &(pcon->arr[findIndex].age));
	printf("请输入联系人性别\n");
	scanf("%s", pcon->arr[findIndex].gander);
	printf("请输入联系人电话\n");
	scanf("%s", pcon->arr[findIndex].tel);
	printf("请输入联系人地址\n");
	scanf("%s", pcon->arr[findIndex].addr);

	printf("修改成功！\n");
}

void ContactFind(Contact* pcon){
	printf("请输入你要查找的联系人姓名\n");
	char name[NAME_MAX];
	scanf("%s", name);
	int findIndex = FindByName(pcon, name);
	if (findIndex < 0) {
		printf("要查找的联系人不存在！\n");
		return;
	}
	//找到了
	printf("%-10s %-4s %-4s %15s %-20s\n", "姓名", "性别", "年龄", "联系电话", "地址");
	printf("%-10s %-4s %-4s %15s %-20s\n",
		pcon->arr[findIndex].name,
		pcon->arr[findIndex].gander,
		pcon->arr[findIndex].age,
		pcon->arr[findIndex].tel,
		pcon->arr[findIndex].addr
	);
}

void ContactShow(Contact* pcon) {
	if (pcon->size <= 0) {
		printf("通讯录人数为 0 ，请添加联系人！\n");	    
	}
	else {
		printf("%-10s %-4s %-4s %15s %-20s\n", "姓名", "性别", "年龄", "联系电话", "地址");
		for (int i = 0; i < pcon->size; i++) {
			printf("%-10s %-4s %-4s %15s %-20s\n",
				pcon->arr[i].name,
				pcon->arr[i].gander,
				pcon->arr[i].age,
				pcon->arr[i].tel,
				pcon->arr[i].addr);
		}
	}
}

void ContactSave(Contact* con) {
	FILE* pwb = fopen("contact.txt", "wb");
	if (pwb == NULL) {
		perror("fopen wb error!\n");
		return;
	}
	//将通讯录数据写⼊⽂件
	for (int i = 0; i < con->size; i++)
	{
		fwrite(con->arr + i, sizeof(Info), 1, pwb);
	}
	printf("通讯录数据保存成功！\n");
}

void ContactDesTroy(Contact* pcon) {
	ContactSave(pcon);
	SLDestory(pcon);
}